package com.lee.chain.service.impl;

import com.lee.chain.entity.ChainOfResponsibility;
import com.lee.chain.mapper.ChainOfResponsibilityMapper;
import com.lee.chain.service.AbstractLoggerHandler;
import com.lee.chain.service.ChainOfResponsibilityService;
import com.lee.utils.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zfl_a
 * @date 2020/8/11
 * @project springboot_design_pattern
 */
@Service
public class ChainOfResponsibilityServiceImpl implements ChainOfResponsibilityService {

    @Autowired
    private ChainOfResponsibilityMapper chainOfResponsibilityMapper ;

    private AbstractLoggerHandler abstractLoggerHandler ;

    @Override
    public AbstractLoggerHandler findTopLogHandler(String kindHandler) {

        if (this.abstractLoggerHandler != null) {
            return this.abstractLoggerHandler;
        }
        // 查询此种类中的第一个handler
        ChainOfResponsibility responsibility = chainOfResponsibilityMapper.findTopChain(kindHandler);
        if (responsibility == null) {
            return null;
        }
        String topHandlerId = responsibility.getHandlerId();
        if (StringUtils.isEmpty(topHandlerId)) {
            return null;
        }
        // 从容器中获取bean
        AbstractLoggerHandler topLogBeanHandler = SpringUtils.getBean(topHandlerId, AbstractLoggerHandler.class);
        if (topLogBeanHandler == null) {
            return null;
        }
        // 获取下一个handlerID
        String nextHandlerId = responsibility.getNextHandlerId();
        // 定定义一个临时变量存放
        AbstractLoggerHandler tempTopLogBeanHandler = topLogBeanHandler;
        while (!StringUtils.isEmpty(nextHandlerId)) {
            // 从容器中获取该nextHandlerId对应的对象
            AbstractLoggerHandler nextLogHandler = SpringUtils.getBean(nextHandlerId, AbstractLoggerHandler.class);
            if (nextLogHandler == null) {
                break;
            }
            // 查询当前handler信息
            ChainOfResponsibility nextLogHandlerResponsibility = chainOfResponsibilityMapper.findCurrentHandler(nextHandlerId);
            if (nextLogHandlerResponsibility == null) {
                break;
            }
            // 当下一个handler为空时退出循环
            nextHandlerId = nextLogHandlerResponsibility.getNextHandlerId();
            tempTopLogBeanHandler.setAbstractLoggerHandler(nextLogHandler);
            tempTopLogBeanHandler = nextLogHandler;
        }
        this.abstractLoggerHandler = topLogBeanHandler;
        return abstractLoggerHandler;

    }
}
